package com.lut.reservation.controller;

import com.lut.reservation.bean.*;
import com.lut.reservation.exception.BusinessException;
import com.lut.reservation.service.SystemService;
import com.lut.reservation.service.UserService;
import com.lut.reservation.util.ResultUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


/**
 * @author zyt
 */
@RestController
@RequestMapping("/api/system/")
public class SystemController {

  @Autowired
  private SystemService systemService;

  @Autowired
  private UserService userService;

  @PostMapping("/login")
  public Result<User> login(UserLogin login) {
    User user = systemService.login(login);
    if (user == null) {
      return ResultUtil.fail("用户名或密码错误");
    }
    return ResultUtil.success(user);
  }

  @PostMapping("/logout")
  public Result<Void> logout(HttpSession session) {
    session.invalidate();
    return ResultUtil.success();
  }

  @PostMapping("/update/password")
  public Result<Void> updatePassword(@SessionAttribute(value = "userId", required = false) Integer userId, @RequestBody UserPassword userPassword) {
    if (userId == null) {
      throw new BusinessException("请先登录！");
    }
    final User user = userService.getById(userId);
    if (!user.getPassword().equals(userPassword.getOldPassword())) {
      throw new BusinessException("密码不正确");
    }
    if (!userPassword.getNewPassword().equals(userPassword.getNewPassword2())) {
      throw new BusinessException("确认密码与新密码不匹配");
    }
    userService.lambdaUpdate()
        .set(User::getPassword, userPassword.getNewPassword())
        .eq(User::getId, userId)
        .update();
    return ResultUtil.success();
  }

  @PostMapping("/update/info")
  public Result<Void> updateInfo(@SessionAttribute(value = "userId", required = false) Integer userId, @RequestBody UserInfo userInfo) {
    if (userId == null) {
      throw new BusinessException("请先登录！");
    }
    User user = new User();
    BeanUtils.copyProperties(userInfo, user);
    user.setId(userId);
    userService.updateById(user);
    return ResultUtil.success();
  }

  @PostMapping("/register")
  public Result<Void> register(@RequestBody User user) {
    user.setReaderNumber("-");
    user.setActivate("on");
    boolean save = userService.save(user);
    if (save) {
      user.setReaderNumber(String.valueOf(1000000 + user.getId()));
      userService.updateById(user);
    }
    return ResultUtil.success();
  }

  @PostMapping("/forget/password")
  public Result<Void> forgetPassword() {

    return ResultUtil.success();
  }
}
